<?php

namespace app\api\controller\v2;

use addons\litestore\model\Litestoregoodsspec;
use addons\litestore\model\Litestoreorderaddress;
use addons\litestore\model\Wxlitestoregoods;
use addons\wechat\library\Config as ConfigService;
use app\admin\model\litestore\Litestoregoods;
use app\admin\model\litestore\Litestoreordergoods;
use app\admin\model\Litestorecart;
use app\admin\model\Orderday;
use app\admin\model\Profitbuy;
use app\admin\model\Useraddress;
use app\admin\model\Useragentwechat;
use app\admin\model\Userrelation;
use app\admin\model\Usersales;
use app\admin\model\Userweixin;
use app\api\service\LepayService;
use app\api\service\MessageService;
use app\api\service\Orderservice;
use app\api\service\ProfitService;
use app\common\controller\Api;
use addons\litestore\model\Litestoreorder;

use addons\third\model\Third;
use EasyWeChat\Factory;
use EasyWeChat\Factory as WXPAY_APP;

class Factoryorder extends Api
{
    protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['callback'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->model = new Litestoreorder;

    }


    public function buyPay()
    {

        $user = $this->auth->getUser();

        $userWxModel = new Userweixin();
        $wx = $userWxModel->where('uid', $user['id'])->find();

        $amount = 100*1000;
        $orderNo = getOrderSn();
        $data = array();
        $data['desc'] = "商家入驻平台保证金";
        $data['openid'] = $wx['openid'];
        $data['orderNo'] = $orderNo;
        $data['amount'] =$amount;
        $data['pay_price'] =$amount;

        $data['callback_url'] = 'https://' . $_SERVER['HTTP_HOST'] . "/api/v2/factoryorder/callback";


        $payService = new LepayService("3910718329", "");
        $ret = $payService->pay2($data);

        error_log("===ret====".json_encode($ret));
        if ($ret['resp_code'] == 0) {


            $factoryOrderModel = new \app\admin\model\Factoryorder();
            $id = $factoryOrderModel->insertGetId(['uid'=>$user['id'],'amount'=>1000,'orderNo'=>$orderNo,'createtime'=>time()]);
            if ($id) {
                $info = array();
                $info['orderNo'] = $orderNo;
                $info['payInfo'] = json_decode($ret['jspay_info'], true);
                $this->success('下单成功', $info);
            } else {
                $this->error("下单失败，请联系客服");
            }

        } else {
            $this->error("下单失败，请联系客服");
        }

    }

    public function callback()
    {

        $param = file_get_contents("php://input");
        error_log("======factory pay=====callback=================" . $param);

        $jsonxml = json_encode(simplexml_load_string($param, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true);
        $orderNo = $result['third_order_id'];
        $status = $result['status'];

        if ($status == 2) {
            $factoryOrderModel = new \app\admin\model\Factoryorder();
            $order = $factoryOrderModel->where('orderNo', $orderNo)->find();
            error_log("==factory==order====".json_encode($order));
            $factoryOrderModel->where('orderNo', $orderNo)->update(['orderStatus' => 'payed']);
        }
        echo "000000";


    }


    public function vipcallback()
    {



        $param = file_get_contents("php://input");

        $jsonxml = json_encode(simplexml_load_string($param, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true);
//        error_log("========1====" . json_encode($result));
        $orderNo = $result['third_order_id'];
        $status = $result['status'];
        error_log("=========vipcallback==============" . $orderNo);

        error_log("=========vipcallback==============" . $status);

        if ($status == 2) {
            $literOrder = new \app\admin\model\litestore\Litestoreorder();
            $order = $literOrder->where('order_no', $orderNo)->find();
            error_log("=========vipcallback==============" . json_encode($order));

            if ($order['pay_price'] * 100 == $result['amount']) {
                $literOrder->where('order_no', $orderNo)->update(['order_status' => 'payed',
                    'pay_time' => time(), 'transaction_id' => $result['out_transaction_id']]);
            }

            $userModel = new \app\admin\model\User();
            $user = $userModel->where('id', $order['user_id'])->find();
            if ($user['group_id'] == 1) {
                $userModel->where('id', $order['user_id'])->update(['group_id' => 2]);
            }
            echo "000000";
            $orderService = new Orderservice();
            $orderService->cacRefAward($order);

        }


    }

    public function Get_order_num()
    {
        $NoPayNum = $this->model->where(['user_id' => $this->user_id, 'pay_status' => '10', 'freight_status' => '10', 'order_status' => '10', 'receipt_status' => '10'])->count();
        $NoFreightNum = $this->model->where(['user_id' => $this->user_id, 'pay_status' => '20', 'freight_status' => '10', 'order_status' => '10', 'receipt_status' => '10'])->count();
        $NoReceiptNum = $this->model->where(['user_id' => $this->user_id, 'pay_status' => '20', 'freight_status' => '20', 'order_status' => '10', 'receipt_status' => '10'])->count();
        return $this->success('', ['NoPayNum' => $NoPayNum, 'NoFreightNum' => $NoFreightNum, 'NoReceiptNum' => $NoReceiptNum]);
    }

    public function my()
    {
        $list = $this->model->getList($this->user_id);
        return $this->success('', $list);
    }

    public function detail()
    {
        $orderNo = $this->request->param('orderNo');


        $liteorderModel = new \app\admin\model\litestore\Litestoreorder();
        $order = $liteorderModel->where('order_no', $orderNo)->find();
        $order['orderTime'] = date('Y-m-d h:i:s', $order['createtime']);
        if (!$order) {
            $this->error('订单不存在');
        }
        $order_id = $order['id'];
        $litestoreordergoods = new \addons\litestore\model\Litestoreordergoods();
        $goods = $litestoreordergoods->where('order_id', $order_id)->select();
        $order['goods'] = $goods;
        $litestoreorderaddress = new Litestoreorderaddress();
        $address = $litestoreorderaddress->where('order_id', $order_id)->find();
        $order['address'] = $address;

        $goodsList = [];
        foreach ($order['goods'] as $index => $item) {
            $item['image'] = cdnurl(explode(",", $item['images'])[0], true);
            $item['sku_image'] = $item['spec']['spec_image'] == '' ? '' : cdnurl($item['spec']['spec_image'], true);
            $goodsList[] = $item;
        }
        $order['goods'] = $goodsList;
        return $this->success('', $order);
    }


    public function cart_pay()
    {
        $order = $this->model->getCart($this->user_id);

        // 创建订单
        if ($this->model->order_add($this->user_id, $order)) {
            // 清空购物车
            $this->model->CarclearAll($this->user_id);

            // 发起微信支付
            if ($this->request->request('type') && $this->request->request('type') == 'gzh') {
                $this->init_wx_pay_for_gzh(true);
                $this->make_wx_pay('wechat');
            } else {
                $this->init_wx_pay_for_wxapp();
                $this->make_wx_pay('wxapp');
            }
        }
        $this->error($this->model->getError() ?: '订单创建失败');
    }

    public function finish()
    {
        $id = $this->request->post("id");
        $order = $this->model;
        if ($order->finish($this->user_id, $id)) {
            return $this->success('');
        }
        return $this->error($order->getError());
    }

    public function cancel()
    {
        $id = $this->request->post("id");
        $order = $this->model->getOrderDetail($id, $this->user_id);

        if ($order->cancel($this->user_id, $id)) {
            return $this->success('');
        }
        return $this->error($order->getError());
    }

    public function order_pay()
    {
        $id = $this->request->post("id");
        $order = $this->model->getOrderDetail($id, $this->user_id);
        if (!$order->checkGoodsStatusFromOrder($order['goods'])) {
            return $this->error($order->getError());
        }
        $this->model = $order;
        // 发起微信支付
        if ($this->request->post('type') && $this->request->post('type') == 'gzh') {
            $this->init_wx_pay_for_gzh(true);
            $this->make_wx_pay('wechat');
        } else {
            $this->init_wx_pay_for_wxapp();
            $this->make_wx_pay('wxapp');
        }
    }

    public function getList()
    {

        $user = $this->auth->getUser();

        $status = $this->request->param('status');
        $where = [];
        $where['user_id'] = $user['id'];
        if ($status == '-1') {
            //全部
            $where['order_status'] = array('<>', 'paying');
        } else if ($status == '1') {
            //待发货
            $where['order_status'] = 'payed';
        } else if ($status == '2') {
            //待收货
            $where['order_status'] = 'transit';
        }
        $liteorderModel = new \app\admin\model\litestore\Litestoreorder();

        $list = $liteorderModel->with(['goods'])
            ->where($where)
            ->order(['createtime' => 'desc'])->limit(50)
            ->select();

        foreach ($list as $key => $val) {
            $good = $val['goods'];
            foreach ($good as $k => $v) {
                $image = cdnurl(explode(",", $v['images'])[0], true);
                $good[$k]['image'] = $image;
            }
        }




        $this->success('', $list);
    }


}
